/*
 * @Author: swc shanwenchao12138@163.com
 * @Date: 2024-01-03 16:17:18
 * @LastEditors: swc
 * @LastEditTime: 2025-03-27 09:58:12
 * @FilePath: \stdsys\src\components\base\nav\o-date-nav\command.ts
 * @Description:
 */
import { ifs, ts, Tsrv } from '@/services';
import { N_oSetupPanel } from '@/types';

class T_cmd {
  // 主组件箱
  private compBox: ifs.I_compBox;

  // 主组件ID
  private compID: string;

  // 主组件实例
  private self: any;
  // 主组refs

  private TCoordination: ifs.I_compCoordination = null;

  private _config: any;

  // 统计字段
  private statisticsFields = [];

  // 关联字段
  private relationField: string = '';

  // 关联表格的所有字段信息
  private relationTableFields: any = [];

  // 主组件created里初始化
  public init(self: any, compBoxInfo: ifs.I_compBoxInfo) {
    this.self = self;
    this.compBox = compBoxInfo.TcompBox;
    this.compID = compBoxInfo.compID;
    this._config = self._config;
    this.statisticsFields = this._config?.statisticsFields;
    this.relationField = this._config?.messageConfig?.emitActions?.search[0]?.msg?.content?.ikey; // ukey
    this.getRelationTableConfig();
  }

  /**
   * @description: 初始化数据————获取所有数据并进行统计数据
   * @param {*}
   * @return {*}
   */
  public getTableData() {
    const targetFields = this.statisticsFields.map(item => item.field);
    const lang = this.self.$i18n.locale || 'en_US';
    const dbType = 'mysql';
    const tableName = this.self._config.mainFun;
    const agreedFields = ['id', this.relationField, ...targetFields];
    const filter = {};
    const funName = this.self._config.mainFun;
    Tsrv.getDataWithOption(
      lang,
      dbType,
      tableName,
      agreedFields,
      filter,
      funName
    ).then(([ok, res, _, err]) => {
      if (ok) {
        if (res.data.total > 0) {
          // this.statistic.total = data.total;
          this.dayTipsHandle(res.data);
          // this.weekTipsHandle(res.data);
          // this.monthTipsHandle(res.data);
          this.getStatisticsDataTips(res.data);
        }
      } else {
        this.self.$msg(err);
      }
    });
  }

  // 数据统计
  private dayTipsHandle(data: any) {
    this.self.attrs.length = 0;
    const rows = Tsrv.utils.clone(data.rows, true);
    for (let i = 0; i < rows.length; i++) {
      const el = rows[i][this.relationField];
      rows[i][this.relationField] = Tsrv.utils.toDateString(el, 'yyyy-MM-dd');
    }
    const allDaysData = Tsrv.utils.groupBy(rows, this.relationField);
    if (allDaysData['']) delete allDaysData[''];
    Object.keys(allDaysData).forEach(key => {
      const oneDayData = allDaysData[key];
      // 展示该天的 description 即：配置字段的统计信息
      const description = this.tipsCount(key, oneDayData);
      description.push(
        `${Tsrv.getI18nByValue('总数据量为')}${oneDayData.length}条`
      );

      const tip = {
        description,
        isComplete: false,
        dates: [Tsrv.utils.toStringDate(key, 'yyyy-MM-dd')],
        color: 'red'
      };
      this.self.attrs.push({
        dates: tip.dates,
        dot: {
          color: tip.color,
          class: tip.isComplete ? 'opacity-75' : ''
        },
        popover: {
          // label: tip.description,
          visibility: 'hover' // visibility，focus，click, hover
        },
        customData: tip
      });
    });
  }

  /**
   * @description: 如果是天数据，计算一天的统计数据
   * @param {*} key：某天的日期
   * @param {*} oneDayData：某天的数据
   * @return {*} msgTips ：统计数据（每个统计字段占一条数据）
   */
  private tipsCount(key: string, oneDayData: any) {
    const msgTips = [];
    const statisticsFields = this.statisticsFields; // 自定义的统计字段
    for (let i = 0; i < statisticsFields.length; i++) {
      const el = statisticsFields[i];
      // 判断字段的 数据类型
      const type = el.type;
      const message = [`${Tsrv.getI18nBySrv(el.field)}`];

      //
      switch (type) {
        case 'number':
          this.fieldForNumber(el, message, oneDayData);
          break;
        case 'string':
          break;
        default:
          break;
      }
      msgTips.push(message.join(''));
    }
    return msgTips;
  }

  /**
   * @description: 如果过滤字段是number类型，则需要判断是否具备下拉属性
   * @param {string} filter 过滤字段详细
   * @param {string} message  字段的 统计信息
   * @param {string} data 某天的数据
   * @return {*}
   */
  private fieldForNumber(filter: any, message: any, data: any) {
    let filterData = Tsrv.utils.clone(data, true);
    let selectionData = Tsrv.utils.clone(filter?.selectionID, true);
    let filterCondition = '';
    // 组装过滤条件（把conditions中的条件组装成 表达式--字符类型）
    filter.conditions.forEach(e => {
      filterCondition += `item['0']${e.operator}${e.value} || `;
    });
    filterCondition = filterCondition.slice(0, -4);
    // 判断字段当为 数字 类型时 是否具备下拉属性
    if (selectionData) {
      selectionData = Tsrv.utils.filter(selectionData, (item, index, arr) => {
        // 把 item['0'] 中的 0 替换成 指定 字段 -- value、lable...
        return eval(
          `${filterCondition.replace(/\['([^']+)'\]/g, "['" + 'value' + "']")}`
        );
      });
      selectionData.forEach(e => {
        filterData = Tsrv.utils.filter(filterData, (item, index, arr) => {
          return item[filter.field] === e.value;
        });
        message.push(
          `为“${Tsrv.getI18nBySrv(e.label)}”的数据有${filterData.length}条、`
        );
      });
      message[message.length - 1] = `${message[message.length - 1].slice(
        0,
        -1
      )}`;
    } else {
      filter.conditions.forEach(e => {
        message.push(`${e.operator}${e.value}且`);
      });
      filterData = Tsrv.utils.filter(filterData, (item, index, arr) => {
        // 把 item['0'] 中的 0 替换成 指定 字段 -- value、lable...
        return eval(
          `${filterCondition.replace(/\['([^']+)'\]/g, `['${filter.field}']`)}`
        );
      });
      message[message.length - 1] = `${message[message.length - 1].slice(
        0,
        -1
      )}的数据`;
      message.push(`共有${filterData.length}条`);
    }
  }

  //
  /**
   * @description: 总数据（包括 所有数据，该月数据，该年数据三个） 统计信息
   * @param {any} data 目前传入的是 关联表的所有数据 （后期如果数据过多，换成网络请求过滤获取数据）
   * @return {*}
   */
  private getStatisticsDataTips(data: any) {
    const statisticalData = this.self.statisticalData;
    const currentDate = new Date();
    const currentYear = currentDate.getFullYear();
    const currentMonth = currentDate.getMonth() + 1;
    // 目前 数据量少时的做法 （获取所有数据的前提下：前端过滤 统计数据）
    // const currentMonthData = data.rows.filter(item => {
    //   const [year, month, day] = item[this.relationField]
    //     .split('-')
    //     .map(Number);
    //   return year === currentYear && month === currentMonth;
    // });
    // const currentYearData = data.rows.filter(item => {
    //   const [year, month, day] = item[this.relationField]
    //     .split('-')
    //     .map(Number);
    //   return year === currentYear;
    // });
    let isWrongData = false;
    const currentMonthData = [];
    const currentYearData = [];
    for (let i = 0; i < data.rows.length; i++) {
      const el = data.rows[i];
      if (
        Tsrv.noValue(el[this.relationField]) ||
        el[this.relationField].indexOf('-') < 0
      ) {
        // 存在 关联日期为空或含不合法日期格式的数据
        isWrongData = true;
        continue;
      }
      const [year, month, day] = el[this.relationField].split('-').map(Number);
      if (year === currentYear) {
        currentYearData.push(el);
        if (month === currentMonth) {
          currentMonthData.push(el);
        }
      }
    }
    if (isWrongData) {
      this.self.$Message.warning(
        Tsrv.getI18nByValue('存在关联日期不合法或为空的数据，请检查！')
      );
    }

    statisticalData.currentMonth = this.tipsCount('', currentMonthData);
    statisticalData.currentYear = this.tipsCount('', currentYearData);
    statisticalData.total = this.tipsCount('', data.rows);
    statisticalData.currentMonth.push(
      `${Tsrv.getI18nByValue('该月数据量为')}${currentMonthData.length}条`
    );
    statisticalData.currentYear.push(
      `${Tsrv.getI18nByValue('该年数据量为')}${currentYearData.length}条`
    );
    statisticalData.total.push(
      `${Tsrv.getI18nByValue('总数据量为')}${data.rows.length}条`
    );

    // 日后数据量多时 通过网络请求过滤数据 再进行数据统计
  }

  /**
   * 加工 “统计字段” 数据结构
   */
  private handleStatisticsData() {
    const targetFields = this.statisticsFields;
    if (targetFields) {
      targetFields.forEach(e => {
        if (e.type === 'number') {
          const selectionID = Tsrv.utils.find(
            this.relationTableFields,
            el => el.field === e.field
          ).selectionID;
          if (selectionID) {
            const lang = this.self.$i18n.locale || 'en_US';
            const dbType = this.self.$store.state.dbType;
            const id = selectionID;
            Tsrv.getSLCData(id, dbType, lang).then(([b, res, msg]) => {
              if (b) {
                e['selectionID'] = res;
              } else {
                this.self.$msg(msg);
              }
            });
          }
        }
      });
      this.getTableData();
    }
  }

  // 获取日期组件关联的 表格组件 配置信息
  private getRelationTableConfig() {
    this.self.$store
      .dispatch('getLayoutConfigAsync', {
        funid: null,
        field: this._config.mainFun,
        type: 'component'
      })
      .then(res => {
        // 获取对应表格所有字段的配置信息
        this.relationTableFields = res?.current?.config?.tableColumns;
        this.handleStatisticsData();
      });
  }

  // 构建组件协作处理类
  public newTcompCoordination(conf: any) {
    // 组件调度
    this.TCoordination = new ts.T_compCoordination(
      conf.name,
      conf.messageConfig,
      {
        setTempToolbarStatusDisabled: (
          p: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
        ) => {
          this.setTempToolbarStatusDisabled(p);
        },
        setTempToolbarStatusUnDisabled: (
          p: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
        ) => {
          this.setTempToolbarStatusUnDisabled(p);
        },
        cleanSubCompData: (
          p: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
        ) => {
          // this.self.cleanSubCompData(p);
        },
        setMask: (p: boolean) => {
          this.self.isMask = p;
        }
      }
    );
  }

  // 处理组件协调
  public receEventCoordination(
    m: N_oSetupPanel.N_comps.I_eventCoordinationMsg
  ) {
    this.TCoordination.receEventCoordination(m)
      .then(([b, msg]) => {})
      .catch(msg => {
        console.error(msg);
        // this.self.$msg(msg);
      });
  }

  private setTempToolbarStatusDisabled(
    p: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
  ) {
    // this.toolbarStatusBak = Tsrv.utils.clone(this.self.toolbar, true);
  }

  private setTempToolbarStatusUnDisabled(
    p: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
  ) {
    // if (this.toolbarStatusBak) {
    //   this.self.toolbar = this.toolbarStatusBak;
    //   this.toolbarStatusBak = null;
    // }
  }

  // 处理组件协调
  public sendEventCoordination(
    type: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
  ) {
    const r = this.TCoordination.sendEventCoordination(type, this.self.$bus)
      .then(([b, msg]) => {})
      .catch(msg => {
        console.error(msg);
        // this.self.$msg(msg);
      });
  }
}
interface I_cmd extends T_cmd {}
export { I_cmd, T_cmd };
